//
//  BTLECentralViewController.swift
//  Rouyu
//
//  Created by 李雷川 on 2017/5/24.
//  Copyright © 2017年 李雷川. All rights reserved.
//

import UIKit
import CoreBluetooth
extension ViewController {

    func initBluetooth(){
        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
    
    }
    
    func scan(){
        centralManager.scanForPeripherals(withServices: [CBUUID.init(nsuuid: UUID(uuidString: TRANSFER_SERVICE_UUID)!)], options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
              centralManager.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
//               centralManager.scanForPeripherals(withServices: nil, options:nil)
    }
    
    func cleanup(){
        centralManager.cancelPeripheralConnection(discoveredPeripheral)
    }

}


extension ViewController:CBCentralManagerDelegate{
    func centralManagerDidUpdateState(_ central: CBCentralManager){
        switch central.state {
        case .unknown:
            print("CBCentralManagerStateUnknown")
            infoLabel.text = "未知"
        case .resetting:
            print("CBCentralManagerStateResetting")
            infoLabel.text = "重置"
        case .unsupported:
            print("CBCentralManagerStateUnsupported")
            infoLabel.text = "不支持"
        case .unauthorized:
            print("CBCentralManagerStateUnauthorized")
            infoLabel.text = "未授权"
        case .poweredOff:
            print("CBCentralManagerStatePoweredOff")
            infoLabel.text = "关闭"
        case .poweredOn:
            print("CBCentralManagerStatePoweredOn")
            infoLabel.text = "打开"
            if(discoveredPeripheral == nil){
                self.scan()
            }
            
        }
    }
    


    //发现周围的设备
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
        if (RSSI.intValue > -15) {
            return
        }
        
        // Reject if the signal strength is too low to be close enough (Close is around -22dB)
        if (RSSI.intValue < -35) {
            return
        }
        print("Discovered  \(String(describing:  peripheral.name)) at \(RSSI)");
        if (self.discoveredPeripheral != peripheral) {
            // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
            self.discoveredPeripheral = peripheral;
              print("Connecting to peripheral \(peripheral)");
            self.centralManager.connect(peripheral, options: nil)
        }
    
    }
    
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){
        print("Connecting to peripheral \(peripheral)");
        guard error == nil else {
            self.cleanup()
            return
        }
        for service in peripheral.services!{
           peripheral.discoverCharacteristics([CBUUID.init(nsuuid: UUID(uuidString: TRANSFER_CHARACTERISTIC_UUID)!)], for: service)
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){
        centralManager .stopScan()
        //外设寻找service
        self.data.removeAll()
        peripheral.discoverServices(nil)
        peripheral.delegate = self
        self.title = peripheral.name
        peripheral.discoverServices([CBUUID.init(nsuuid: UUID(uuidString: TRANSFER_SERVICE_UUID)!)])
     
    }
    

    
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
            print("Failed to connect to \(String(describing: error))");
        self.cleanup()
    }
    

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?){
        self.discoveredPeripheral = nil
        self.scan()
        
    }
}

extension ViewController:CBPeripheralDelegate{

    func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {
        debugPrint("didDiscoverIncludedServicesFor");
    }
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        debugPrint("didDiscoverCharacteristicsFor")
        guard error == nil else {
            self.cleanup()
            return
        }
        for characteristic in service.characteristics!{
            if(characteristic.uuid.isEqual(CBUUID.init(nsuuid: UUID(uuidString: TRANSFER_CHARACTERISTIC_UUID)!))){
               peripheral.setNotifyValue(true, for: characteristic)
            }
        }
    }
    
//    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
//        debugPrint("didWriteValueFor")
//    }
//    
//    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
//  
//    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        debugPrint(" didUpdateValueFor characteristic")
        debugPrint("didUpdateValueFor")
        guard error == nil else {
            return
        }
        if let value = characteristic.value{
            data.append(value)
            textView.text = String.init(data: data, encoding: .utf8)
        }
        
    }
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        debugPrint(" didUpdateValueFor characteristic")
        guard error == nil else {
            return
        }
        guard(characteristic.uuid.isEqual(CBUUID.init(nsuuid: UUID(uuidString: TRANSFER_CHARACTERISTIC_UUID)!)) == true) else{
            return
        }
        if(characteristic.isNotifying){
            debugPrint(" didUpdateNotificationStateFor characteristic is \(characteristic)")
        }
        else{
            self.centralManager.cancelPeripheralConnection(peripheral)
        }
    }
}
